package com.hxd.otc.utils.hyphenate;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.hxd.otc.BuildConfig;
import com.hxd.otc.api.Constant;
import com.hxd.otc.base.BaseApplication;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.home.activity.HyphenateKeFuChatActivity;
import com.hxd.otc.module.login.bean.AccountBean;
import com.hxd.otc.module.my.model.UserModel;
import com.hxd.otc.net.BaseObserver;
import com.hxd.otc.utils.EncryptUtils;
import com.hxd.otc.utils.LogUtils;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.helpdesk.Error;
import com.hyphenate.helpdesk.callback.Callback;
import com.hyphenate.helpdesk.easeui.UIProvider;
import com.hyphenate.helpdesk.easeui.util.IntentBuilder;

import io.rong.imlib.common.DeviceUtils;

/**
 * 环信相关操作
 */
public class HyphenateKeFuUtil {

    private static HyphenateKeFuUtil instance;
    // 是否登录环信账户
    private boolean isLogin;

    public static HyphenateKeFuUtil getInstance() {
        if (instance == null) {
            synchronized (HyphenateKeFuUtil.class) {
                if (instance == null) {
                    instance = new HyphenateKeFuUtil();
                }
            }
        }
        return instance;
    }

    private HyphenateKeFuUtil() {
    }

    public boolean isLogin() {
        return isLogin;
    }

    public void register() {
        if (isLogin) {
            logout();
            return;
        }
        AccountBean userInfo = UserHelper.getUserInfo();
        final String csUsername = userInfo.getCsUsername();
        final String csPass = userInfo.getCsPass();

        if (UserHelper.isLogin() && !TextUtils.isEmpty(csUsername) && !TextUtils.isEmpty(csPass)) {
            if (userInfo.getIsRegisteredCs() == 0) {
                UserModel.getInstance().easemobRegister(csUsername, csPass, new BaseObserver<String>() {
                    @Override
                    public void onNext(@NonNull String msg, @NonNull String s) {
                        ChatClient.getInstance().login(csUsername, csPass, mCallback);
                    }

                    @Override
                    public void onError(int errType, @NonNull String errMessage) {
                        //注册失败
                    }
                }, null);
            } else {
                ChatClient.getInstance().login(csUsername, csPass, mCallback);
            }
        } else {
            final String randomUserName = EncryptUtils.getMd5(DeviceUtils.getDeviceId(BaseApplication.getInstance()));
            ChatClient.getInstance().register(randomUserName, randomUserName, new Callback() {
                @Override
                public void onSuccess() {
//                    LogUtils.e("onSuccess: " + "网络连接不可用，请检查网络"  );
                    ChatClient.getInstance().login(randomUserName, randomUserName, mCallback);
                }

                @Override
                public void onError(int errorCode, String s) {
                    if (errorCode == Error.NETWORK_ERROR) {
//                    LogUtils.e("creat_onError: " + "网络连接不可用，请检查网络" + errorCode);
                    } else if (errorCode == Error.USER_ALREADY_EXIST) {
//                        LogUtils.e( "creat_onError: " + "用户已经存在" + errorCode);
                        ChatClient.getInstance().login(randomUserName, randomUserName, mCallback);
                    } else if (errorCode == Error.USER_AUTHENTICATION_FAILED) {
//                        LogUtils.e( "creat_onError: " + "无开放注册权限" + errorCode);
                    } else if (errorCode == Error.USER_ILLEGAL_ARGUMENT) {
//                        LogUtils.e( "creat_onError: " + "用户名不合法" + errorCode);
                    } else {
//                        LogUtils.e( "creat_onError: " + "注册失败!" + errorCode);
                    }
                }

                @Override
                public void onProgress(int i, String s) {
//                Log.i(TAG, "creat_onProgress: " + s);
                }
            });
        }

    }

    public void logout() {
        ChatClient.getInstance().logout(true, new Callback() {
            @Override
            public void onSuccess() {
                isLogin = false;
                register();
            }

            @Override
            public void onError(int i, String s) {
                ChatClient.getInstance().logout(false, new Callback() {
                    @Override
                    public void onSuccess() {
                        isLogin = false;
                        register();
                    }

                    @Override
                    public void onError(int i, String s) {
                    }

                    @Override
                    public void onProgress(int i, String s) {
                    }
                });
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }


    private Callback mCallback = new Callback() {
        @Override
        public void onSuccess() {
            isLogin = true;
            LogUtils.d("connectHyphenateKeFu success");
        }

        @Override
        public void onError(int i, String s) {
            LogUtils.e("connectHyphenateKeFu error:" + i + "  " + s);
        }

        @Override
        public void onProgress(int i, String s) {
            LogUtils.e("connectHyphenateKeFu onProgress:" + i + "  " + s);
        }
    };

    public void onLineChat(Activity activity) {

//        String name;
//        String email = "";
//
//        if (UserHelper.isLogin()) {
//            name = UserHelper.getRealName();
//            email = UserHelper.getEmail();
//            if (TextUtils.isEmpty(email)) {
//                email = UserHelper.getMobile();
//            }
//        } else {
//            name = android.os.Build.BRAND + "_" + android.os.Build.MODEL;
//        }
        Intent intent = new IntentBuilder(activity)
                .setServiceIMNumber(Constant.HyphenateKeFu.DEFAULT_CUSTOMER_ACCOUNT) //获取地址：kefu.easemob.com，“管理员模式 > 渠道管理 > 手机APP”页面的关联的“IM服务号”
                .setTitleName("WOTC客服")
                .setTargetClass(HyphenateKeFuChatActivity.class)
                .build();
        activity.startActivity(intent);
    }


    /**
     * 环信客服
     */
    public void initHyphenateKeFu() {
        ChatClient.Options options = new ChatClient.Options();
        options.setAppkey(Constant.HyphenateKeFu.DEFAULT_CUSTOMER_APPKEY);//必填项，appkey获取地址：kefu.easemob.com，“管理员模式 > 渠道管理 > 手机APP”页面的关联的“AppKey”
        options.setTenantId(Constant.HyphenateKeFu.DEFAULT_TENANT_ID);//“管理员模式 > 设置 > 企业信息”页面的“租户ID”

        // Kefu SDK 初始化
        if (!ChatClient.getInstance().init(BaseApplication.getInstance(), options)) {
            return;
        }
        // Kefu EaseUI的初始化
        UIProvider.getInstance().init(BaseApplication.getInstance());
        //后面可以设置其他属性

        // 设置为true后，将打印日志到logcat, 发布APP时应关闭该选项
        ChatClient.getInstance().setDebugMode(BuildConfig.DEBUG);
    }

}
